package com.example.admin.xxxxxx;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by admin on 2018/1/7.
 */

public class condition extends Activity implements Button.OnClickListener {

    String ip;
    Button shutdown;
    Button add;
    Button reduce;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.condition);
        shutdown = (Button) findViewById(R.id.shutdown);
        add = (Button) findViewById(R.id.add);
        reduce = (Button) findViewById(R.id.reduce);
        shutdown.setOnClickListener(this);
        add.setOnClickListener(this);
        reduce.setOnClickListener(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        ip = bundle.getString("ip");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shutdown:
                new post().execute(ip,"100");
                break;
            case R.id.add:
                new post().execute(ip,"101");
                break;
            case R.id.reduce:
                new post().execute(ip,"102");
                break;
        }


    }


    class post extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(condition.this,"发送完成",Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean == true) {
                Toast.makeText(condition.this, "true", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected Boolean doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("type", "condition");
                jsonObject.put("value1", params[0]);
                jsonObject.put("value2", params[1]);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                Socket socket = new Socket(MainActivity.IP, 3001);
                OutputStream outputStream = socket.getOutputStream();

                outputStream.write(jsonObject.toString().getBytes());
                outputStream.flush();
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

            return true;
        }
    }


}
